from django.conf import settings
from django.shortcuts import render
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from celery_tasks.sms.tasks import send_sms_code
from meiduo.libs.yuntongxun.sms import CCP
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from users.serialziers import UserSerialziers, UserDetailSerializer, EmailSerializer, VerifySerizlizers
from users.models import User


# Create your views here.
# 短信验证的业务逻辑
class SMSCodeView(APIView):

    def get(self, request, mobile):
        # 判断发送频率 控制60s
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s' % mobile)
        if flag:
            return Response({'errors': '请求过于频繁'}, status=402)
        # 生成一个短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)

        # 保存短信验证码
        pl = conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('sms_flag_%s' % mobile, 60, 1)
        pl.execute()  # 传递指令  写入redis

        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '1'], 1)
        send_sms_code.delay(mobile, sms_code)

        # 返回结果
        return Response({'message': 'ok'})


# 用户名数量的判断
class UserNameView(APIView):
    def get(self, request, username):
        # 查询数据对象数量
        count = User.objects.filter(username=username).count()

        return Response(
            {
                'count': count
            }
        )


# 用户名数量的判断
class MobileCountView(APIView):
    def get(self, request, mobile):
        # 查询数据对象数量
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {
                'count': count
            }
        )


# 用户数据的保存
class UserView(CreateAPIView):
    serializer_class = UserSerialziers

    # def post(self, request, *args, **kwargs):
    #
    #     # 验证数据
    #     ser = self.get_serializer(data=request.data)
    #
    #     ser.is_valid()
    #
    #     print(ser.errors)
    #
    #     response=super().post(request)
    #
    #     return response


# 用APIView和RetrieveAPIView对比
# class UserDetailView(APIView):
#     def get(self,request):
#         # 获取用户对象
#         user=request.user
#         # 序列化返回
#         ser=UserDetailSerializer(user)
#         return Response(ser.data)


# 显示用户个人中心信息
class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer

    # queryset = User.objects.all()

    def get_object(self):
        return self.request.user


# 更新邮箱
class UserEmailView(UpdateAPIView):
    serializer_class = EmailSerializer

    # def put(self,request):
    #
    #     # 获取数据
    #
    #     # 验证数据
    #
    #     # 更新数据
    #
    #     # 返回结果

    def get_object(self):
        return self.request.user


# # 邮箱验证# 方式 一（原始APIView方式 ）
# class VerifyEmail(APIView):
#
#     def get(self, request):
#
#         # 获取token数据
#         token = request.query_params.get('token', None)
#         if token is None:
#             return Response({'errors': '缺少token'}, status=400)
#
#         # 解密验证token
#         tjs = TJS(settings.SECRET_KEY, 300)
#
#         try:
#             data = tjs.loads(token)
#         except:
#             return Response({'errors': '无效token'}, status=400)
#
#         # 获取加密的用户信息
#         id = data['id']
#
#         # 查询用户
#         user = User.objects.get(id=id)
#
#         # 更新验证状态
#         user.email_active = True
#         user.save()
#
#         # 返回结果  ok
#         return Response({'message': 'ok'})


# 方式二（GenericAPIView方式 ）
# class VerifyEmail(GenericAPIView):
#
#     serializer_class = VerifySerizlizers
#
#     def get(self,request):
#
#         # 获取token数据
#         data=request.query_params
#
#         # 验证数据
#         ser=self.get_serializer(data=data)
#         ser.is_valid()
#
#         # 更新验证状态
#         ser.save()
#
#         # 返回结果  ok
#         return Response({'message':'ok'})


# 方式三（重写get_serializer）的方法
class VerifyEmail(CreateAPIView):
    serializer_class = VerifySerizlizers

    def get_serializer(self, *args, **kwargs):
        return super().get_serializer(data=self.request.query_params)

    def get(self, request):
        super().post(request)
        # 返回结果  ok
        return Response({'message': 'ok'})


# 重写用户的登录
class UserLoginView(ObtainJSONWebToken):
    """
        重写登录
    """

    def post(self, request, *args, **kwargs):
        # 调用父类方法，完成用户登录验证操作
        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            # 合并购物车
            response = merge_cart_cookie_to_redis(request, response, user)
            return response

        return response
